const mysql = require('mysql2/promise')
const config = require('./config')

async function checkDbStatus () {
  try {
    const connection = await mysql.createConnection({
      host: config.database.host,
      port: config.database.port,
      user: config.database.user,
      password: config.database.password,
      database: config.database.name
    })

    console.log('🔍 检查当前数据库状态...')

    // 检查表是否存在
    const [tables] = await connection.execute('SHOW TABLES')
    console.log('\n📋 数据库中的表:')
    console.table(tables)

    // 检查authors表
    try {
      const [authors] = await connection.execute(
        'SELECT * FROM authors LIMIT 5'
      )
      console.log('\n👥 authors表数据:')
      console.table(authors)
    } catch (error) {
      console.log('⚠️ authors表不存在或查询失败:', error.message)
    }

    // 检查novels表结构
    try {
      const [novelStructure] = await connection.execute('DESCRIBE novels')
      console.log('\n📚 novels表结构:')
      console.table(novelStructure)

      const [novels] = await connection.execute(
        'SELECT id, title, author, author_id FROM novels LIMIT 5'
      )
      console.log('\n📖 novels表数据样本:')
      console.table(novels)
    } catch (error) {
      console.log('⚠️ novels表查询失败:', error.message)
    }

    // 检查外键约束
    try {
      const [foreignKeys] = await connection.execute(`
        SELECT CONSTRAINT_NAME, TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
        FROM information_schema.KEY_COLUMN_USAGE 
        WHERE REFERENCED_TABLE_SCHEMA = '${config.database.name}'
        AND TABLE_NAME = 'novels'
      `)
      console.log('\n🔗 外键约束:')
      console.table(foreignKeys)
    } catch (error) {
      console.log('⚠️ 外键约束查询失败:', error.message)
    }

    await connection.end()
    console.log('\n✅ 数据库状态检查完成')
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message)
  }
}

checkDbStatus()
